import type { MenuListResponse } from "@/api/login/types";
import type { RouteRecordRaw } from "vue-router";
import Layout from "@/layout/Layout.vue";
import router from "@/router";

/**
 * 批量添加路由
 * @param routes 路由数组 
 */
export const addRoutes = (routes: RouteRecordRaw[]) => {
    routes.forEach(route => router.addRoute({ ...route }))
}

/**
 * 生成动态路由tree
 * @param menus 菜单树形列表
 * @returns 
 */
export const buildRoutes = ((menus: MenuListResponse[], modules: any): RouteRecordRaw[] => {
    const routes: RouteRecordRaw[] = []
    menus.forEach((item) => {
        routes.push({
            name: item.name,
            path: item.path,
            meta: {
                title: item.title,
                icon: item.icon
            },
            component: item.type == 'dir' ? Layout : modules[item.component],
            children: item.children ? buildRoutes(item.children, modules) : []
        })
    })
    return routes
})

/**
 * 通过path获取路由
 * @param path 
 * @returns 
 */
export const getRouteByPath = (path: string): RouteRecordRaw | undefined => {
    const routes: RouteRecordRaw[] = router.getRoutes();
    return routes.find(item => item.path === path);
}
